const config = require('@tuniu/light-config')(__dirname + '/app/config/');
const os = require('os');
const express = require('express');
const log4js = require('log4js');
const Core = require('@tuniu/core');
const lightCommon = require('@tuniu/light-common');
const helper = require('@tuniu/light-helper');

const app = express();
const pkg = lightCommon.package(config.importPaths);

module.exports = {
    getAppConfig(){
        return config;
    },

    createApplication() {
        log4js.configure(config.log4js);

        app.enable('trust proxy');
        app.set('appName', config.appName);

        global.__config__ = config;
        Object.assign(app.locals, helper, {__config__: config});
        // 加载插件
        config.loadPlugins(app, {
            contexts: {
                core: Core(config),
                utils: lightCommon.utils,
                validator: pkg.import('tuniu.common.validator'),
                log4js: log4js,
                logger: log4js.getLogger('app')
            }
        });

        app.getPlugin('lightMvc').loadMiddlewares(config); // 加载中间件.
        app.getPlugin('lightMvc').addRoutes(); // 添加light-mvc的路由规则.

        return app;
    },

    startTspClient(){
        // 启动tsp和服务器监听.
        (function (tspConfig, remoteServices) {
            let tspClient = require('@tuniu/tspclient')(tspConfig);
            tspClient.collector = tspClient.ServiceCollector();
            if (remoteServices) {
                tspClient.collector.addRemoteServices(remoteServices);
            }
            tspClient.collector.start();
            tspClient.caller = tspClient.ServiceCaller();
            app.getPlugin('lightMvc').setAppContext('tspClient', tspClient);
        })(config.tsp, config.remote.services);
    }
};